//
//  BusDataManager.m
//  SQLIteTest
//
//  Created by 修勇 黄 on 12-7-1.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "BusDataManager.h"
#import "XXSQLiteOpe.h"


NSString *const BusDataManagerDataBaseFileChangeNSNotification =@"BusDataManagerDataBaseFileChangeNSNotification";

NSString *const BusDataManagerCurrentDataBaseDataUpdateNotification=@"BusDataManagerCurrentDataBaseDataUpdateNotification";

@interface BusDataManager (Private)

//搜索经过站点的所有线路 参数 站点id 返回的数据为所有的数据没有处理过

-(NSArray *)querAllListPassTheStopID:(NSString *)stopID;

-(BOOL)queryStationWithLineID:(NSString *)lineID type:(NSString *)type index:(NSString *)index isGo:(BOOL)go;

-(NSInteger)checkDic:(NSDictionary *)dic isContainArray:(NSArray *)array;//if contain return index or retian -1

-(NSDictionary *)lineInfoWithLineID:(NSString *)lineID type:(NSString *)type dataArray:(NSArray *)array;

@end

@implementation BusDataManager

@synthesize busDataFilePath=_busDataFilePath;

@synthesize cityName=_cityName;

@synthesize date=_date;


static BusDataManager *busManager=nil;

-(void)dealloc{

    [_busDataFilePath release];
    [dataOpe release];
    [super dealloc];
}

-(id)init{

    self=[super init];
    if (self) {
        dataOpe=[[XXSQLiteOpe alloc]init];
    }
    return self;
}

-(NSString *)cityName{

    NSString *sql=[NSString stringWithFormat:@"select cityName from information"];
    NSArray *array=[dataOpe queryData:sql error:NULL];
    if (array&&array.count>0) {
        NSDictionary *dic=[array objectAtIndex:0];
        return [dic objectForKey:@"cityName"];
    }else {
        return nil;
    }
}

-(NSString *)date{
   
    NSString *sql=[NSString stringWithFormat:@"select date from information"];
    NSArray *array=[dataOpe queryData:sql error:NULL];
    if (array&&array.count>0) {
        NSDictionary *dic=[array objectAtIndex:0];
        return [dic objectForKey:@"date"];
    }else {
        return nil;
    }
}

-(NSArray *)queryAllBusDataUpdateByPathList:(NSArray *)pathList{

    
    NSMutableArray *tempArray=[NSMutableArray new];
    for (int i=0; i<pathList.count; i++) {
        NSString *path=[pathList objectAtIndex:i];
        XXSQLiteOpe *tempOpe=[[XXSQLiteOpe alloc]initWithFilePath:path];
        NSArray *tempResult=[tempOpe queryData:@"select date from information" error:nil];
        NSDictionary *dateDic=[tempResult objectAtIndex:0];
        NSArray *tempCityNameResult=[tempOpe queryData:@"select cityName from information" error:nil];
        NSDictionary *cityNameDic=[tempCityNameResult objectAtIndex:0];

        [tempOpe release];
        NSMutableDictionary *tempDic=[NSMutableDictionary new];
        [tempDic addEntriesFromDictionary:dateDic];

        [tempDic addEntriesFromDictionary:cityNameDic];

        [tempArray addObject:tempDic];
    }
    return [tempArray autorelease];
}

//设置 bus 数据库文件路径

-(void)setBusDataFilePath:(NSString *)busDataFilePath{

    if ([busDataFilePath isEqualToString:_busDataFilePath]) {
        return;
    }
    NSMutableDictionary *notDic=[NSMutableDictionary dictionary];
    
    if (_busDataFilePath) {
        [notDic setObject:_busDataFilePath forKey:@"BusManagerLastFilePath"];
    }
    
    if (busDataFilePath) {
        [notDic setObject:busDataFilePath forKey:@"BusManagerNewFilePath"];
    }
    
    [_busDataFilePath release];
    _busDataFilePath=[busDataFilePath retain];
    
    dataOpe.filePath=busDataFilePath;
    
    [[NSNotificationCenter defaultCenter]postNotificationName:BusDataManagerDataBaseFileChangeNSNotification object:notDic];
}



//模糊搜索线路列表 参数:线路的名字

-(NSArray *)fuzzyQueryBusLineListWithFuzzyWord:(NSString *)text{

    NSString *sql=[NSString stringWithFormat:@"select * from lines where lineName like '%%%@%%'",text];
    return [dataOpe queryData:sql error:NULL];
}

//搜索线路的所经过的站点 参数:线路的id

-(NSDictionary *)queryBusAllStationWithLineID:(NSString *)lineID{

    NSString *sql=[NSString stringWithFormat:@"select relation.stopID,relation.type,relation.theIndex,stops.stopName from relation inner join stops on relation.stopID=stops.stopID where lineID='%@'",lineID];
    NSArray *array=[dataOpe queryData:sql error:NULL];
    NSMutableArray *tempGoArray=[NSMutableArray new];
    NSMutableArray *tempBackArray=[NSMutableArray new];
    
    for (int i=0; i<array.count; i++) {
        NSDictionary *dic=[array objectAtIndex:i];
        NSInteger tempTheIndex=[[dic objectForKey:@"theIndex"] intValue];
        
        if ([[dic objectForKey:@"type"] isEqualToString:@"0"]) {
            if (tempTheIndex!=tempGoArray.count) {
                [tempGoArray addObject:dic];
            }else
                [tempGoArray insertObject:dic atIndex:[[dic objectForKey:@"theIndex"]intValue]];
        }else {
            if (tempBackArray.count!=tempTheIndex) {
                [tempBackArray addObject:dic];
            }else
                [tempBackArray insertObject:dic atIndex:[[dic objectForKey:@"theIndex"]intValue]];
        }
    }
    NSDictionary *resultDic=[NSDictionary dictionaryWithObjectsAndKeys:tempGoArray,@"go",tempBackArray,@"back", nil];
    [tempGoArray release];
    [tempBackArray release];
    return resultDic;
}

//模糊搜索站点列表 参数:站点的名字

-(NSArray *)fuzzyQueryBusStopListWithFuzzyWord:(NSString *)text{

    NSString *sql=[NSString stringWithFormat:@"select * from stops where stopName like '%%%@%%'",text];
    
    return [dataOpe queryData:sql error:NULL];
}

//搜索经过站点的所有线路 参数 站点id

-(NSArray *)queryBusLineListPassTheStopID:(NSString *)stopID{

    NSArray *array=[self querAllListPassTheStopID:stopID];
   
    if (array) {
        NSMutableArray *tempResult=[NSMutableArray arrayWithArray:array];
        NSMutableArray *newResult=[NSMutableArray new];
        
        for(int i=0;tempResult.count>0;i=0){
        
            NSDictionary *dic=[tempResult objectAtIndex:i];
            NSMutableDictionary *tempCheckDic=[NSMutableDictionary dictionaryWithDictionary:dic];
           [tempCheckDic removeObjectForKey:@"type"];
            NSMutableDictionary *theResultDic=[NSMutableDictionary dictionaryWithDictionary:tempCheckDic];
            
            BOOL dicIsGo=YES;
            
            if ([[dic objectForKey:@"type"] isEqualToString:@"0"]) {
                [tempCheckDic setObject:@"1" forKey:@"type"];
                dicIsGo=YES;
            }else {
                [tempCheckDic setObject:@"0" forKey:@"type"];
                dicIsGo=NO;
            }
            
            if ([tempResult containsObject:tempCheckDic]) {
                [theResultDic setObject:@"0" forKey:@"type"];
                [tempResult removeObject:tempCheckDic];
            }else {
                if (dicIsGo) {
                    [theResultDic setObject:@"1" forKey:@"type"];
                }else {
                    [theResultDic setObject:@"-1" forKey:@"type"];
                }
            }
            [newResult addObject:theResultDic];
            
            [tempResult removeObject:dic];
        }
        return [newResult autorelease];
    }
    return [NSArray array];
}

//搜索是否有直达的线路 参数 其实站点id

-(NSArray *)queryDirectBusLineStartStopID:(NSString *)startStop endStopID:(NSString *)endStop{

    NSString *sql=[NSString stringWithFormat:@"select r1.lineID,r1.type,lines.lineName from relation r1,relation r2  inner join lines on lines.lineID=r1.lineID where r1.stopID='%@' and r2.stopID='%@' and r1.lineID=r2.lineID and r1.type=r2.type and r1.theIndex>r2.theIndex;",startStop,endStop];
    return [dataOpe queryData:sql error:nil];
}


//搜索转乘线路 参数 起始站点 

-(NSArray *)queryTwoRideStartStopID:(NSString *)startStop endStopID:(NSString *)endStop{

    NSArray *passStartStopArray=[self querAllListPassTheStopID:startStop];
    NSArray *passEndStopArray=[self querAllListPassTheStopID:endStop];
    
   // NSLog(@"passStart %@",passStartStopArray);
    //NSLog(@"passEnd %@",passEndStopArray);
    
    NSString *deleteTempOne=@"Drop table temp1";
    NSString *deleteTempTwo=@"drop table temp2";
    [dataOpe handleData:deleteTempOne parameter:nil error:nil];
    [dataOpe handleData:deleteTempTwo parameter:nil error:nil];
    NSString *creatTempOne=@"CREATE TABLE temp1(s_lineID varchar(255),s_type varchar(255),s_stopID varchar(255),s_stopName varchar(255),s_theIndex varchar(255))";
    NSString *creatTempTwo=@"CREATE TABLE temp2(e_lineID varchar(255),e_type varchar(255),e_stopID varchar(255),e_stopName varchar(255),e_theIndex varchar(255))";
    
    if ([dataOpe handleData:creatTempOne parameter:nil error:nil]) {
        
          
        for (NSDictionary *dic in passStartStopArray) {
            [self queryStationWithLineID:[dic objectForKey:@"lineID"] type:[dic objectForKey:@"type"] index:[dic objectForKey:@"theIndex"] isGo:YES];
        }
        
    }else {
        [dataOpe handleData:deleteTempOne parameter:nil error:nil];
        [dataOpe handleData:deleteTempTwo parameter:nil error:nil];
        return nil;
    }
    
    if ([dataOpe handleData:creatTempTwo parameter:nil error:nil]) {
        
        for (NSDictionary *dic in passEndStopArray) {
            [self queryStationWithLineID:[dic objectForKey:@"lineID"] type:[dic objectForKey:@"type"] index:[dic objectForKey:@"theIndex"] isGo:NO];
        }
        
        NSString *sameStopSql=@"select * from temp1 t1,temp2 t2 where t1.s_stopID=t2.e_stopID";
       // NSLog(@"same %@",sameStopSql);
        NSArray *result=[dataOpe queryData:sameStopSql error:nil];
        [dataOpe handleData:deleteTempOne parameter:nil error:nil];
        [dataOpe handleData:deleteTempTwo parameter:nil error:nil];
        
        NSMutableArray *tempInfoResultArray=[NSMutableArray new];
        NSMutableArray *sameTempMutableArray=[NSMutableArray arrayWithArray:result];
      
        while (sameTempMutableArray.count!=0) {
            NSDictionary *tempSameDic=[sameTempMutableArray objectAtIndex:0];
            NSInteger index=[self checkDic:tempSameDic isContainArray:tempInfoResultArray];
            if (index==-1) {
                NSMutableDictionary *tempNewDic=[NSMutableDictionary dictionary];
                NSString *s_lineID_key=@"s_lineID";
                NSString *s_type_key=@"s_type";
                NSString *e_lineID_key=@"e_lineID";
                NSString *e_type_key=@"e_type";
                [tempNewDic setObject:[tempSameDic objectForKey:s_lineID_key] forKey:s_lineID_key];
                [tempNewDic setObject:[tempSameDic objectForKey:s_type_key] forKey:s_type_key];
                [tempNewDic setObject:[tempSameDic objectForKey:e_lineID_key] forKey:e_lineID_key];
                [tempNewDic setObject:[tempSameDic objectForKey:e_type_key] forKey:e_type_key];
                [tempNewDic setObject:[self lineInfoWithLineID:[tempSameDic objectForKey:s_lineID_key] type:[tempSameDic objectForKey:s_type_key] dataArray:passStartStopArray] forKey:@"startLineInfo"];
                NSDictionary *tempEndLineInfoDic=[self lineInfoWithLineID:[tempSameDic objectForKey:e_lineID_key] type:[tempSameDic objectForKey:e_type_key] dataArray:passEndStopArray] ;
               // NSLog(@"dic %@",tempEndLineInfoDic);
                [tempNewDic setObject:tempEndLineInfoDic forKey:@"endLineInfo"];
               
                NSMutableArray *tempArray=[NSMutableArray new];
                NSDictionary *theSameStopDic=[NSDictionary dictionaryWithObjectsAndKeys:[tempSameDic objectForKey:@"s_stopID"],@"stopID",[tempSameDic objectForKey:@"s_stopName"],@"stopName",[tempSameDic objectForKey:@"s_theIndex"],@"theIndex", nil];
                [tempArray addObject:theSameStopDic];
                [tempNewDic setObject:tempArray forKey:@"sameStop"];
                [tempInfoResultArray addObject:tempNewDic];
                [tempArray release];
            }else {
                NSMutableDictionary *tempInfoDic=[tempInfoResultArray objectAtIndex:index];
                NSMutableArray *tempSameStopArray=[tempInfoDic objectForKey:@"sameStop"];
                NSDictionary *tempNewDic=[NSDictionary dictionaryWithObjectsAndKeys:[tempSameDic objectForKey:@"s_stopID"],@"stopID",[tempSameDic objectForKey:@"s_stopName"],@"stopName",[tempSameDic objectForKey:@"s_theIndex"],@"theIndex", nil];
                [tempSameStopArray addObject:tempNewDic];
            }
        
            [sameTempMutableArray removeObjectAtIndex:0];
        }
        return [tempInfoResultArray autorelease];
        
    }else {
        [dataOpe handleData:deleteTempOne parameter:nil error:nil];
        [dataOpe handleData:deleteTempTwo parameter:nil error:nil];
        return nil;
    }
}

// 查询 线路的单行线路

-(NSArray *)querySingleBusLineByBusID:(NSString *)lineID type:(NSString *)type fromIndex:(NSString *)fromIndex toIndex:(NSString *)toIndex{

    NSString *sql=[NSString stringWithFormat:@"select relation.stopID,relation.type,relation.theIndex,stops.stopName from relation inner join stops on relation.stopID=stops.stopID where lineID='%@' and type='%@' and theIndex BETWEEN %@ and %@",lineID,type,fromIndex,toIndex];
    //NSLog(@"sql %@",sql);
    NSArray *array=[dataOpe queryData:sql error:NULL];
    return array;
}


//获取所有的收藏

-(NSArray *)queryAllCollection{

    NSString *sql=@"select * from collection";
    return [dataOpe queryData:sql error:NULL];
}

-(BOOL)addCollectionWithType:(NSString *)type info:(NSString *)info{

    NSString *sql=[NSString stringWithFormat:@"insert into collection (type,info) values('%@','%@')",type,info];
    return [dataOpe handleData:sql parameter:nil error:nil];
}

#pragma mark -
#pragma mark -Private Method

-(NSArray *)querAllListPassTheStopID:(NSString *)stopID{

    NSString *sql=[NSString stringWithFormat:@"select lines.lineID,lines.lineName,lines.lineInfo,relation.type,relation.theIndex from relation inner join lines on lines.lineID=relation.lineID where stopID='%@'",stopID];
    NSArray *array=[dataOpe queryData:sql error:NULL];
    return array;
}

-(BOOL)queryStationWithLineID:(NSString *)lineID type:(NSString *)type index:(NSString *)index isGo:(BOOL)go{

    //if ([type isEqualToString:@"-1"]) {
        NSMutableString *sql=[NSMutableString stringWithFormat:@"select  relation.lineID,relation.type,relation.stopID,stops.stopName,relation.theIndex from relation inner join stops on stops.stopID=relation.stopID where type='%@' and lineID='%@'",type,lineID];
        if (go) {
            [sql appendFormat:@" AND theIndex>%@",index];
            sql=[NSString stringWithFormat:@"insert into temp1 %@",sql];
        }else {
            [sql appendFormat:@" AND theIndex<%@",index];
            sql=[NSString stringWithFormat:@"insert into temp2 %@",sql];
        }
        return [dataOpe handleData:sql parameter:nil error:nil];
       
  //  }
    
    /*else if ([type isEqualToString:@"1"]) {
        
        NSMutableString *sql=[NSMutableString stringWithFormat:@"select  relation.lineID,relation.type,relation.stopID,stops.stopName,relation.theIndex from relation inner join stops on stops.stopID=relation.stopID where type='%@' and lineID='%@'",type,lineID];
        if (go) {
            [sql appendFormat:@" AND theIndex>%@",index];
            sql=[NSString stringWithFormat:@"insert into temp1 %@",sql];
        }else {
            [sql appendFormat:@" AND theIndex<%@",index];
            sql=[NSString stringWithFormat:@"insert into temp2 %@",sql];
        }
        return [dataOpe handleData:sql parameter:nil error:nil];
       
    }else {
        NSMutableString *sql=[NSMutableString stringWithFormat:@"select  relation.lineID,relation.type,relation.stopID,stops.stopName,relation.theIndex from relation inner join stops on stops.stopID=relation.stopID where type='0' and lineID='%@'",lineID];
        if (go) {
            [sql appendFormat:@" AND theIndex>%@",index];
            sql=[NSString stringWithFormat:@"insert into temp1 %@",sql];
        }else {
            [sql appendFormat:@" AND theIndex<%@",index];
            sql=[NSString stringWithFormat:@"insert into temp2 %@",sql];
        }
       
        if ([dataOpe handleData:sql parameter:nil error:nil]==NO) {
            return NO;
        }
        sql=[NSMutableString stringWithFormat:@"select relation.lineID,relation.type,relation.stopID,stops.stopName,relation.theIndex from relation inner join stops on stops.stopID=relation.stopID where type='1' and lineID='%@'",lineID];
        if (go) {
            [sql appendFormat:@" AND theIndex>%@",index];
        }else {
            [sql appendFormat:@" AND theIndex<%@",index];
        }
        return [dataOpe handleData:sql parameter:nil error:nil];
    
    }*/
}

-(NSInteger)checkDic:(NSDictionary *)dic isContainArray:(NSArray *)array{

    for (NSDictionary *tempDic in array) {
        if ([[tempDic objectForKey:@"s_lineID"] isEqualToString:[dic objectForKey:@"s_lineID"]]&&[[tempDic objectForKey:@"e_lineID"] isEqualToString:[dic objectForKey:@"e_lineID"]]) {
            return [array indexOfObject:tempDic];
        }
    }
    
    return -1;
}

-(NSDictionary *)lineInfoWithLineID:(NSString *)lineID type:(NSString *)type dataArray:(NSArray *)array{

   // NSLog(@"lineid %@  %@  %@",lineID,type,array);
     for (NSDictionary *tempDic in array) {
        // NSLog(@"id %@ lineid %@ type %@ type %@",lineID,[tempDic objectForKey:@"lineID"],type,[tempDic objectForKey:@"type"]);
        if ([[tempDic objectForKey:@"lineID"] isEqualToString:lineID]&&[[tempDic objectForKey:@"type"]isEqualToString:type]) {
            return tempDic;
        }
    }
    
    return nil;
}

#pragma mark -
#pragma mark  Segment Method

+(BusDataManager *)currentBusDataManager{

    @synchronized(self)
	{
        if (busManager==nil) {
            busManager=[[super allocWithZone:NULL]init];
        }
    }
    
    return busManager;
}

+(id)allocWithZone:(NSZone *)zone
{
	return[[self currentBusDataManager]retain];
}


- (id)copyWithZone:(NSZone *)zone
{	
    return self;
}


-(id)retain
{
	return self;
}


-(NSUInteger)retainCount
{
	return NSUIntegerMax;
}


-(id)autorelease
{
	return self;
}

-(oneway void)release{

    
}

@end
